<template>
  <el-dialog
    v-if="isVisible"
    title="上传文件"
    :visible.sync="isVisible"
    width="800px"
    append-to-body
    @closed="dialogClosed"
  >
    <div class="container">
      <template v-if="dictType">
        <div class="function-item">
          <el-form ref="form" :model="uploadForm" label-width="130px">
            <el-form-item label="选择上传文件类型">
              <el-select v-model="uploadForm.fileType" placeholder="请选择活动区域">
                <el-option
                  v-for="(item, index) in fileTypeList"
                  :label="item.label"
                  :value="item.value"
                  :key="index"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </div>
        <div class="upload-file-list-wrap" v-show="viewFileList.length > 0">
          <div v-for="(item, index) in viewFileList" :key="index">
            <ul class="upload-file-list">
              <li class="file-label">{{ format(item.fileType) }}</li>
              <li :title="item.name">
                {{ item.name }}
                <a href="javascript:;" @click="deleteFile(item)">删除</a>
              </li>
            </ul>
          </div>
        </div>
      </template>
      <el-upload
        class="upload-demo"
        ref="uploadRef"
        :drag="isDrag"
        :action="actionUrl"
        :multiple="multiple"
        :auto-upload="computedAutoUpload"
        :on-preview="handlePreview"
        :on-remove="handleRemove"
        :before-remove="beforeRemove"
        :before-upload="beforeUpload"
        :data="{ access_token: userInfo.access_token, path: 'scm/maindata' }"
        :on-progress="handleProgress"
        :on-exceed="handleExceed"
        :on-success="handleSuccess"
        :on-change="uploadChange"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          <template v-if="isDrag"
            >将文件拖到此处，或<em>{{ text }}</em></template
          >
          <template v-else
            ><em>{{ text }}</em></template
          >
        </div>
        <div class="el-upload__tip" slot="tip" v-if="fileType.length"
          >只能上传{{ fileType.join(',') }}文件<template v-if="fileSize > 0"
            >，且不超过{{ fileSize }}MB</template
          ></div
        >
      </el-upload>
    </div>
    <div slot="footer" v-if="dictType">
      <el-button size="small" class="dialog-btn cancel-dialog" type="primary" @click="cancelSelect"
        >取消</el-button
      >
      <el-button
        size="small"
        class="dialog-btn confirm-dialog"
        type="primary"
        @click="confirmUpload"
        >确认上传</el-button
      >
    </div>
  </el-dialog>
</template>

<script>
  import baseUrl from '@/common/config';
  import API from '@/api/dataBase';
  import path from 'path';
  import { dateTimeFormat } from '@/filters/index';
  export default {
    name: 'UploadDialog',
    props: {
      isDrag: {
        type: Boolean,
        default: true,
      },
      multiple: {
        type: Boolean,
        default: true,
      },
      autoUpload: {
        type: Boolean,
        default: true,
      },
      // 上传的回调方法
      uploadHandler: {
        type: Function,
      },
      text: {
        type: String,
        default: '点击上传',
      },
      // 文件大小单位M
      fileSize: {
        type: Number,
        default: 0,
      },
      // 支持的文件格式['png','gif','jpeg','jpg']
      fileType: {
        type: Array,
        default: () => [],
      },
      dictType: {
        type: String,
        default: '',
      },
    },
    data() {
      return {
        isVisible: false,
        actionUrl: '',
        uploadForm: {
          fileType: null,
        },
        fileTypeList: [],
        viewFileList: [],
      };
    },
    computed: {
      computedAutoUpload() {
        if (this.dictType) {
          return false;
        }
        return this.autoUpload;
      },
    },
    mounted() {
      this.actionUrl = baseUrl + API.OSS_UPLOAD_API;
      this.fileTypeList = this.dictListMap[this.dictType] || [];
    },
    methods: {
      openDialog() {
        this.isVisible = true;
        this.viewFileList = [];
        this.uploadForm = { ...this.uploadForm, fileType: null };
      },
      dialogClosed() {
        this.isVisible = false;
      },
      handleRemove(file, fileList) {
        console.log(file, fileList);
      },
      handlePreview(file) {
        console.log(file, '文件');
      },
      beforeUpload(file) {
        console.log('文件', file);
        const { name, size } = file;
        // 文件格式化校验
        if (this.fileType.length) {
          const supportFileType = this.fileType?.join('|');
          const fileExtname = path.extname(name).substring(1);
          console.log(supportFileType, fileExtname);
          if (!new RegExp('(' + supportFileType + ')', 'i').test(fileExtname)) {
            this.$message.warning(`文件格式不正确,只能上传${this.fileType}其中一种`);
            return false;
          }
        }
        if (this.fileSize > 0) {
          // 文件大小
          if (size > this.fileSize * 1024 * 1024) {
            this.$message.warning(`文件过大,请上传小于${this.fileSize}MB的文件`);
            return false;
          }
        }
        return true;
      },
      handleExceed(files, fileList) {
        this.$message.warning(
          `当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
            files.length + fileList.length
          } 个文件`
        );
      },
      beforeRemove(file) {
        console.log(file);
        // return this.$confirm(`确定移除 ${file.name}？`);
      },
      // 上传时
      handleProgress(event, file, fileList) {
        console.log(event, file, fileList, '文件上传时');
        this.loading.startLoading('正在上传中....');
      },
      //上传成功
      handleSuccess(res, file) {
        this.loading.endLoading();
        debugger;
        if (res.code === 0) {
          let obj = {
            attachmentName: file.name,
            createBy: this.userInfo.userName,
            gmtCreate: dateTimeFormat(new Date()),
            attachmentPath: res.data.attachmentPath,
            attachmentKey: res.data.attachmentKey,
            fileType: file.fileType,
          };
          if (this.computedAutoUpload) {
            this.$emit('upload', obj);
            this.uploadHandler && this.uploadHandler(obj);
            this.dialogClosed();
          } else {
            debugger;
            // this.viewFileList.push(obj);
            debugger;
            this.$emit('upload', obj);
            // this.$emit(
            //   'upload',
            //   this.viewFileList.filter((item) => item.attachmentName)
            // );
          }
          this.$message.success('上传成功');
        } else {
          this.$message({
            showClose: true,
            message: res.msg,
            type: 'error',
          });
        }
      },
      uploadChange(_, fileList) {
        if (!this.uploadForm.fileType) {
          this.$message.error('请先选择文件类型');
          return;
        }
        const lastItem = fileList.pop();
        fileList.push({ ...lastItem, fileType: this.uploadForm.fileType });
        this.viewFileList = fileList.filter((item) => item.fileType);
      },
      cancelSelect() {
        this.$refs.uploadRef.clearFiles();
        this.dialogClosed();
      },
      confirmUpload() {
        if (this.viewFileList.length <= 0) {
          this.$message({
            showClose: true,
            message: '请选择文件',
            type: 'error',
          });
          return;
        }
        this.$refs.uploadRef.submit();
        this.dialogClosed();
      },
      deleteFile(item) {
        this.viewFileList = this.viewFileList.filter((e) => {
          return e.name != item.name;
        });
      },
      format(item) {
        let fileName = '-';
        this.fileTypeList.forEach((val) => {
          if (val.value === item) {
            fileName = val.label;
          }
        });
        return fileName;
      },
    },
  };
</script>

<style lang="scss" scoped>
  .container {
    ::v-deep {
      .el-upload-dragger,
      .el-upload {
        width: 100% !important;
        background-color: #fff;
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        box-sizing: border-box;
        width: 360px;
        height: 180px;
        text-align: center;
        position: relative;
        overflow: hidden;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
      }
      .el-icon-upload {
        line-height: 50px;
        font-size: 67px;
      }
      .el-upload__text em {
        color: #409eff;
        font-style: normal;
      }
      .el-upload-dragger {
        border: none !important;
      }
      .el-upload-list {
        display: none !important;
      }
    }
    .upload-file-list {
      padding-left: 20px;
      list-style: none;
      display: flex;
      flex-direction: row;
      a {
        padding-left: 10px;
      }
    }
  }
</style>
